package com.training.admin.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.annotation.Dao;
import com.training.admin.dao.DynamicReportDao;
import com.training.admin.dao.ProjectTraineeDao;
import com.training.admin.dao.TraineeDao;
import com.training.admin.entity.dynamic.report.DynamicReport;
import com.training.admin.entity.dynamic.report.DynamicReportData;
import com.training.admin.entity.upload.UploadResult;
import com.training.admin.handler.FileHandler;
import com.training.admin.handler.support.FileStorage;
import com.training.admin.service.DynamicReportService;

/**
 * 
 * @author Rockett
 *
 */
@Service("dynamicReportService")
public class DynamicReportServiceImpl extends DataServiceImpl<DynamicReport> implements DynamicReportService{
	private static final Logger logger = LoggerFactory.getLogger(DynamicReportServiceImpl.class);

	@Dao
    private ProjectTraineeDao projectTraineeDao;
	@Dao
    private TraineeDao traineeDao;
	@Dao
    private DynamicReportDao dynamicReportDao;
    @Autowired
    private FileHandler fileHandler;

 

	/* (non-Javadoc)
	 * @see com.training.admin.service.DynamicReportService#listByName(java.lang.String)
	 */
	@Override
	public List<DynamicReport> listByName(String name) {
		return dynamicReportDao.listByName(name);
	}


	/* (non-Javadoc)
	 * @see com.training.admin.service.ProjectTraineeService#upload(org.springframework.web.multipart.MultipartFile)
	 */
    @SuppressWarnings("unchecked")
    @Override
	public List<UploadResult> upload(MultipartFile file,DynamicReport dynamicReport) {
        try {
            
            // 1. save file
            FileStorage fileStorage = new FileStorage("dynamic-report/upload", "dynamic-report-upload"+dynamicReport.getName()+(new Date()).getTime(), FilenameUtils.getExtension(file.getOriginalFilename()));
            String fullPathName=fileHandler.save(fileStorage, file.getInputStream());
            dynamicReport.setFileName(fileStorage.getFileName());
            dynamicReport.setFullFilePath(fullPathName);
            // 2. parse file to 
            Map<String, Object> result  = this.parse( file,dynamicReport);
            
            //save file generate from column header as template :::todo
            
            // 3. save 
            List<DynamicReportData> dynamicReportDataList = (List<DynamicReportData>) result.get("reportdata");
            for (DynamicReportData dynamicReportData : dynamicReportDataList) {
            	if(dynamicReportData.isEmpty())
            		continue;
            	dynamicReportData.setDynamicReport(dynamicReport);
            	genericDaoSupport.save(dynamicReportData);
            }
            
            logger.trace("#upload() - batch upload success");
            return (List<UploadResult>) result.get("uploadResults");
            
        } catch (Exception e) {
            logger.error("#upload() - batch upload driver fail, exception is [{}]", e);
            throw BusinessException.newInstance("500", "批量上传失败，" + e.getMessage());
        }
	}


    /**
     * @param login
     * @param file
     * @return
     */
    private Map<String, Object> parse(MultipartFile file,DynamicReport dynamicReport) {
        
        // 0. prepare data
        Map<String, Object> result = new HashMap<String, Object>();
        List<DynamicReportData> dynamicReportDataList = new ArrayList<DynamicReportData>();
        List<UploadResult> uploadResults = new ArrayList<UploadResult>();
        DataFormatter formatter = new DataFormatter();

        try {
            
            logger.trace("#parse() - Starting parsing upload file.");

            // 1. get workbook
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            
            // 2. get sheet and rows
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rows = sheet.iterator();
            
            // 3. construct trainees
            while (rows.hasNext()) {
                
                Row row = rows.next();
                int rowNum = row.getRowNum();
                
                if (rowNum < 1) {
                	//set column names
                	String colStr="";
                	 for(int j=0;j<25;j++){
                     	String val = formatter.formatCellValue(row.getCell(j)); 
                     	if(!StringUtils.isBlank(val))
                     	colStr+=","+val;
                     }
                	 if(StringUtils.isBlank(colStr)){
                		 throw new Exception ("Upload file format error!");
                	 }
                	 dynamicReport.setColumns(colStr.substring(1));
                	 genericDaoSupport.save(dynamicReport);
                	 continue;
                }
                DynamicReportData dynamicReportData = new DynamicReportData();
                dynamicReportData.setDynamicReport(dynamicReport);
                for(int j=0;j<25;j++){
                	String val = formatter.formatCellValue(row.getCell(j)); 
                	dynamicReportData.setColValue(j,val);
                }
                dynamicReportDataList.add(dynamicReportData);
                //genericDaoSupport.save(dynamicReportData);

                
            }
            
            logger.trace("#parse() - Finishing parsing file with {} records.", dynamicReportDataList.size());
            
        } catch (Exception e) {
            logger.error("#parse() - Finishing parsing file with errors.", e);
        }
        
        result.put("reportdata", dynamicReportDataList);
//        result.put("quitDrivers", quitDrivers);
        if (CollectionUtils.isNotEmpty(uploadResults)) {
            result.put("uploadResults", uploadResults);
        }
        
        return result;
        
    } 

}
